package com.ruben.simplegraphql.provider;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruben.simplegraphql.pojo.po.RoleInfo;
import com.ruben.simplegraphql.pojo.po.UserInfo;
import com.ruben.simplegraphql.pojo.po.UserRole;
import com.ruben.simplegraphql.pojo.vo.RoleVO;
import com.ruben.simplegraphql.pojo.vo.UserVO;
import com.ruben.simplegraphql.util.ConvertUtil;
import graphql.GraphQL;
import graphql.execution.instrumentation.Instrumentation;
import graphql.execution.instrumentation.tracing.TracingInstrumentation;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import io.github.vampireachao.stream.plugin.mybatisplus.Database;
import io.github.vampireachao.stream.plugin.mybatisplus.Many;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import static graphql.schema.idl.TypeRuntimeWiring.newTypeWiring;

/**
 * GraphQLProvider
 *
 * @author VampireAchao
 * @since 2022/9/25
 */
@Component
public class GraphQLProvider {
    private GraphQL graphQL;

    @PostConstruct
    public void init() throws IOException {
        URL url = ResourceUtils.getURL("classpath:schema.graphqls");
        String sdl = IoUtil.readUtf8((BufferedInputStream) url.getContent());
        GraphQLSchema graphqlSchema = buildSchema(sdl);

        Instrumentation instrumentation = new TracingInstrumentation();

        this.graphQL = GraphQL.newGraphQL(graphqlSchema).instrumentation(instrumentation).build();
    }

    private GraphQLSchema buildSchema(String sdl) {
        TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(sdl);
        RuntimeWiring runtimeWiring = buildWiring();
        SchemaGenerator schemaGenerator = new SchemaGenerator();
        return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
    }

    @SuppressWarnings("unchecked")
    private RuntimeWiring buildWiring() {
        return RuntimeWiring.newRuntimeWiring()
                .type(newTypeWiring("Query")
                        .dataFetcher("users", environment -> {
                            Page<UserInfo> paramPage = BeanUtil.mapToBean(environment.getArguments(), Page.class, false, CopyOptions.create());
                            UserInfo userInfo = BeanUtil.mapToBean(environment.getArguments(), UserInfo.class, false, CopyOptions.create());
                            return Database.page(paramPage, Wrappers.lambdaQuery(userInfo)).convert(new UserVO()::convert);
                        })
                        .dataFetcher("roles", environment -> {
                            String name = environment.getArgument("name");
                            List<RoleInfo> queryRoles = Database.list(Wrappers.lambdaQuery(RoleInfo.class).like(RoleInfo::getRoleName, name));
                            return ConvertUtil.convertList(queryRoles, RoleVO.class);
                        })
                )
                .type(newTypeWiring("User")
                        .dataFetcher("roles", environment -> {
                            UserVO userVO = environment.getSource();
                            List<String> roleIds = Many.query(userVO.getId(), UserRole::getUserId, UserRole::getRoleId);
                            return Many.query(roleIds, RoleInfo::getId, new RoleVO()::convert);
                        })
                )
                .type(newTypeWiring("Role")
                        .dataFetcher("users", environment -> {
                            RoleVO roleVO = environment.getSource();
                            List<Long> userIds = Many.query(roleVO.getId(), UserRole::getRoleId, UserRole::getUserId);
                            return Many.query(userIds, UserInfo::getId, new UserVO()::convert);
                        })
                )
                .build();
    }

    @Bean
    public GraphQL graphQL() {
        return graphQL;
    }

}
